package com.yunti.springboot.service.impl;

import cn.hutool.json.JSONObject;
import com.yunti.springboot.service.WechatService;
import com.yunti.springboot.vo.Result;
import com.yunti.springboot.vo.req.GetConfigReq;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class WechatServiceImpl implements WechatService {

    @Resource
    protected StringRedisTemplate stringRedisTemplate;

    //wx5f0ddc0a4131aaa5
    //1f52f36166d3ca8bce3ba9c8b9d4f1e3
    @Override
    public Result getConfig(GetConfigReq getConfigReq) {
        String jsapiTicket = stringRedisTemplate.opsForValue().get("jsapi_ticket");
        if (jsapiTicket == null || jsapiTicket.equals("")) {
            String accessToken = getAccesstoken();
            try {
                URL url = new URL("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + accessToken + "&type=jsapi");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
                con.disconnect();

                System.out.println(content.toString());
                JSONObject jsonObject = new JSONObject(content);

                String ticketObj = jsonObject.getStr("ticket");

                if (ticketObj != null) {
                    jsapiTicket = ticketObj;
                    stringRedisTemplate.opsForValue().set("jsapi_ticket", (String) jsapiTicket, 7200, TimeUnit.SECONDS);

                }

            } catch (Exception e) {

            }
        }
        System.out.println(jsapiTicket);

        String noncestr = "Wm3WZYTPz0wzccnW";
        long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
        String url = getConfigReq.getUrl();

        String str = "jsapi_ticket=" + jsapiTicket + "&noncestr=Wm3WZYTPz0wzccnW&timestamp=" + timestamp + "&url=" + url;
        System.out.println(str);
        String signature = "";
        try {
            signature = sha1Encrypt(str);
            System.out.println(signature);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String,String> result = new HashMap<>();
        result.put("appId","wx5f0ddc0a4131aaa5");
        result.put("timestamp",timestamp + "");
        result.put("nonceStr",noncestr);
        result.put("signature",signature);

        return Result.success(result);
    }

    private String getAccesstoken() {
        String accessToken = stringRedisTemplate.opsForValue().get("access_token");
//        stringRedisTemplate.opsForValue().set(TOKEN_KEY + userName, result,10, TimeUnit.HOURS);
        if (accessToken == null || accessToken.equals("")) {
            try {
                URL url = new URL("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5f0ddc0a4131aaa5&secret=1f52f36166d3ca8bce3ba9c8b9d4f1e3");
                HttpURLConnection con = (HttpURLConnection) url.openConnection();
                con.setRequestMethod("GET");

                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer content = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    content.append(inputLine);
                }
                in.close();
                con.disconnect();

                System.out.println(content.toString());
                JSONObject jsonObject = new JSONObject(content);

                String accessTokenObj = jsonObject.getStr("access_token");

                if (accessTokenObj != null) {
                    accessToken = accessTokenObj;
                    stringRedisTemplate.opsForValue().set("access_token", (String) accessTokenObj, 7200, TimeUnit.SECONDS);
                    System.out.println(accessToken);
                }

            } catch (Exception e) {

            }

        }
        return accessToken;
    }

    public static String sha1Encrypt(String input) throws Exception {
        MessageDigest digest = MessageDigest.getInstance("SHA-1");
        byte[] encodedHash = digest.digest(input.getBytes(StandardCharsets.UTF_8));

        StringBuilder hexString = new StringBuilder();
        for (byte b : encodedHash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }

        return hexString.toString();
    }
}
